<template>
  <Form :data="model" @ok="onSave">
    <div class="flex pl24 pr24 mb16">
      <FormItem field="name" no-style required feedback>
        <Input class="f1" v-model="model.name" placeholder="一级名称" />
      </FormItem>
      <div class="w8" />
      <FormItem field="value" no-style required feedback>
        <Input class="f1" v-model="model.value" placeholder="一级字典值" />
      </FormItem>
    </div>
    <draggable item-key="id" v-model="model.children" animation="300" handle=".arco-icon-drag-dot-vertical">
      <template #item="{ element, index }">
        <div class="flex aic mb8">
          <IconDragDotVertical class="cm" size="24" style="stroke-width: 3" />
          <FormItem :field="`children.${index}.name`" no-style required feedback>
            <Input class="f1" v-model="element.name" placeholder="二级名称" />
          </FormItem>
          <div class="w8" />
          <FormItem :field="`children.${index}.code`" no-style required feedback>
            <Input class="f1" v-model="element.code" placeholder="二级字典值" />
          </FormItem>
          <div class="w24 tar cp">
            <IconClose @click="model.children.splice(index, 1)" size="22" style="stroke-width: 1" v-if="model.children.length > 2" />
          </div>
        </div>
      </template>
    </draggable>
    <div class="tac pl24 pr24 pt8">
      <Button shape="circle" long @click="onAdd">
        <IconPlus />
        添加一行
      </Button>
    </div>
    <template #op>
      <ModalButton :loading="loading" />
    </template>
  </Form>
</template>

<script setup>
import { Button, Form, FormItem, Input, Message, ModalButton } from '@idmy/ui'
import { IconClose, IconPlus, IconDragDotVertical } from '@idmy/ui-icon'
import { useLoading } from '@idmy/core'
import { reactive } from 'vue'
import { createOrUpdateDict } from './services'
import Draggable from 'vuedraggable'

const props = defineProps({ model: Object })

const template = {
  pid: 0,
  level: 0,
  name: null,
  code: null,
  value: null,
  nameEn: null,
  remark: null,
  sort: 1000,
}

const model = reactive({ ...template, children: [] })
const onAdd = () => model.children.push({ ...template, level: 1 })
onAdd()
onAdd()

const [onSave, loading] = useLoading(async () => {
  await createOrUpdateDict(model)
  Message.success('保存成功')
  Modal.ok(model)
})
</script>
